namespace BLP_Converter
{
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    public partial class MainForm : Form
    {
        private string formCaption;

        public MainForm()
        {
            InitializeComponent();
            blpOutput.DragDrop += new DragEventHandler(blpOutput_DragDrop);
            blpOutput.AllowDrop = true;
            formCaption = this.Text;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                OpenFile(openFileDialog.FileName);
            }
        }

        private void MainForm_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }

        private void MainForm_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            Task.Factory.StartNew(() =>
            {
                if (Path.GetExtension(files[0]).ToLower() == ".blp")
                {
                    OpenFile(files[0]);
                }
                else
                {
                    MessageBox.Show("Unsupported file extension!", "Error");
                }
            });
        }

        private void blpOutput_DragDrop(object sender, DragEventArgs e)
        {
            MainForm_DragDrop(sender, e);
        }

        private void OpenFile(string fileName)
        {
            this.Invoke((Action)delegate
            {
                blpOutput.Clear();
                this.Text = formCaption + " - " + fileName;
                blpOutput.Lines = Program.OpenBLP(fileName);
            });
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            blpOutput.SelectAll();
            blpOutput.Copy();
        }
    }
}